package com.xy.blog.core.exception.handle;

import com.xy.blog.core.exception.BaseException;
import com.xy.blog.core.exception.IllegalInputArgumentException;
import com.xy.blog.core.exception.contants.ErrorCode;
import com.xy.blog.core.springmvc.result.base.data.RestResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.FileNotFoundException;
import java.util.Locale;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description: Controller 统一异常处理
 * @date 2019/10/23 1:02
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Autowired
    private MessageSource messageSource;

    /**
     * 全局业务异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public Object exceptionHandler(BaseException ex) throws FileNotFoundException {
        String errorCode = ex.getErrorCode();
        if (StringUtils.isEmpty(errorCode)) {
            errorCode = ErrorCode.SYS_ERROR;
        }
        String message ;
        if (StringUtils.isEmpty(ex.getMessage())) {
            message = messageSource.getMessage(errorCode, ex.getArgs(), Locale.getDefault());
        } else {
            message = ex.getMessage();
        }
        logger.error(message + ": {}", ExceptionUtils.getStackTrace(ex));
        return RestResult.error(errorCode, message);
    }

    /**
     * 接口参数校验
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(IllegalInputArgumentException.class)
    public Object exceptionHandler(HttpServletRequest request, IllegalInputArgumentException ex) {
        String errorCode = ex.getErrorCode();
        String message = messageSource.getMessage(String.valueOf(errorCode), ex.getArgs(), Locale.getDefault());
        logger.error("【" + message + "】" + ExceptionUtils.getMessage(ex));
        logger.error(ExceptionUtils.getStackTrace(ex));
        return RestResult.error(errorCode, ex.getMessage());
    }


    @ExceptionHandler(Exception.class)
    public RestResult exceptionHandler(HttpServletRequest request, Exception ex) {
        //TODO
        ex.printStackTrace();
//        String message = messageSource.getMessage(String.valueOf(errorCode), ex.getArgs(), Locale.getDefault());
        return RestResult.error("99", request.getRequestURI());
    }




}
